﻿using System;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Sunny.UI;
using LogisticsAndong.Comm;
using LogisticsAndong.Business;
using LogisticsAndong.Model;
using Leeder.Logger;
using LeederGlobal;
using System.Collections.Concurrent;
using System.Collections.Generic;
using LogisticsAndong.Handle;

namespace LogisticsAndong.Forms
{
    public partial class FrmSystemSet : UIPage
    {
        /// <summary>
        /// 判断窗体是否首次加载
        /// </summary>
        bool isLoad = true;

        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());

        public event Action DgvUpadteEvent;
        LogisticsAndongHandler logisticsAndongHandler;
        MaterialDirectionBLL bllMaterialDirection = new MaterialDirectionBLL();
        SignalLampDirectionBLL bllSignalLampDirection = new SignalLampDirectionBLL();
        UnpackingDirectionBLL bllUnpackingDirection = new UnpackingDirectionBLL();

        public FrmSystemSet()
        {
            InitializeComponent();
            logisticsAndongHandler = LogisticsAndongHandler.CreateInstance();
        }

        private void FrmSystemSet_Load(object sender, EventArgs e)
        {
            if (!isLoad)
                return;
            isLoad = false;

            //开捆
            dgvKk.AutoGenerateColumns = false;
            dgvKk.AllowUserToAddRows = false;
            dgvKk.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvKk.ReadOnly = true;
            dgvKk.AddColumn("序号", "ID", 33);
            dgvKk.AddColumn("工程名称", "UnpackingName", 33);
            dgvKk.AddColumn("IP地址", "IpAddress", 34);

            //顺引顺建
            dgvDmsy.AutoGenerateColumns = false;
            dgvDmsy.AllowUserToAddRows = false;
            dgvDmsy.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvDmsy.ReadOnly = true;
            dgvDmsy.AddColumn("序号", "ID", 5);
            dgvDmsy.AddColumn("工程名称", "MaterialName", 20);
            dgvDmsy.AddColumn("IP地址", "IpAddress", 15);
            dgvDmsy.AddColumn("工程台数", "ProjectCount", 15);
            dgvDmsy.AddColumn("出发台数", "StartTransportCount", 15);
            dgvDmsy.AddColumn("车型标识", "CarMark", 15);
            dgvDmsy.AddColumn("信号源标识", "SignalMark", 15);

            dgvXmsy.AutoGenerateColumns = false;
            dgvXmsy.AllowUserToAddRows = false;
            dgvXmsy.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvXmsy.ReadOnly = true;
            dgvXmsy.AddColumn("序号", "ID", 5);
            dgvXmsy.AddColumn("工程名称", "MaterialName", 20);
            dgvXmsy.AddColumn("IP地址", "IpAddress", 15);
            dgvXmsy.AddColumn("工程台数", "ProjectCount", 15);
            dgvXmsy.AddColumn("出发台数", "StartTransportCount", 15);
            dgvXmsy.AddColumn("车型标识", "CarMark", 15);
            dgvXmsy.AddColumn("信号源标识", "SignalMark", 15);

            dgvZwsy.AutoGenerateColumns = false;
            dgvZwsy.AllowUserToAddRows = false;
            dgvZwsy.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvZwsy.ReadOnly = true;
            dgvZwsy.AddColumn("序号", "ID", 5);
            dgvZwsy.AddColumn("工程名称", "MaterialName", 20);
            dgvZwsy.AddColumn("IP地址", "IpAddress", 15);
            dgvZwsy.AddColumn("工程台数", "ProjectCount", 15);
            dgvZwsy.AddColumn("出发台数", "StartTransportCount", 15);
            dgvZwsy.AddColumn("车型标识", "CarMark", 15);
            dgvZwsy.AddColumn("信号源标识", "SignalMark", 15);

            dgvNzp.AutoGenerateColumns = false;
            dgvNzp.AllowUserToAddRows = false;
            dgvNzp.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvNzp.ReadOnly = true;
            dgvNzp.AddColumn("序号", "ID", 5);
            dgvNzp.AddColumn("工程名称", "MaterialName", 20);
            dgvNzp.AddColumn("IP地址", "IpAddress", 15);
            dgvNzp.AddColumn("工程台数", "ProjectCount", 10);
            dgvNzp.AddColumn("出发台数", "StartTransportCount", 10);
            dgvNzp.AddColumn("出发工程工程数", "TriggerProjectCount", 10);
            dgvNzp.AddColumn("车型标识", "CarMark", 15);
            dgvNzp.AddColumn("信号源标识", "SignalMark", 15);

            dgvPx.AutoGenerateColumns = false;
            dgvPx.AllowUserToAddRows = false;
            dgvPx.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvPx.ReadOnly = true;
            dgvPx.AddColumn("序号", "ID", 5);
            dgvPx.AddColumn("工程名称", "MaterialName", 20);
            dgvPx.AddColumn("IP地址", "IpAddress", 15);
            dgvPx.AddColumn("工程台数", "ProjectCount", 15);
            dgvPx.AddColumn("出发台数", "StartTransportCount", 15);
            dgvPx.AddColumn("车型标识", "CarMark", 15);
            dgvPx.AddColumn("信号源标识", "SignalMark", 15);

            //拉绳安灯
            dgvSL0.AutoGenerateColumns = false;
            dgvSL0.AllowUserToAddRows = false;
            dgvSL0.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL0.ReadOnly = true;
            dgvSL0.AddColumn("序号", "ID", 10);
            dgvSL0.AddColumn("工程名称", "LampName", 20);
            dgvSL0.AddColumn("信号灯", "SignalLampMappingID", 20);
            dgvSL0.AddColumn("出发台数", "TriggerCount", 10);
            dgvSL0.AddColumn("出发延时台数", "TriggerDelayCount", 10);
            dgvSL0.AddColumn("结束延时台数", "EndDelayCount", 10);
            dgvSL0.AddColumn("单数/双数链", "ChainMark", 10);
            dgvSL0.AddColumn("状态", "Enable", 10);

            dgvSL1.AutoGenerateColumns = false;
            dgvSL1.AllowUserToAddRows = false;
            dgvSL1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL1.ReadOnly = true;
            dgvSL1.AddColumn("序号", "ID", 10);
            dgvSL1.AddColumn("工程名称", "LampName", 20);
            dgvSL1.AddColumn("信号灯", "SignalLampMappingID", 20);
            dgvSL1.AddColumn("出发台数", "TriggerCount", 10);
            dgvSL1.AddColumn("出发延时台数", "TriggerDelayCount", 10);
            dgvSL1.AddColumn("结束延时台数", "EndDelayCount", 10);
            dgvSL1.AddColumn("单数/双数链", "ChainMark", 10);
            dgvSL1.AddColumn("状态", "Enable", 10);

            dgvSL2.AutoGenerateColumns = false;
            dgvSL2.AllowUserToAddRows = false;
            dgvSL2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL2.ReadOnly = true;
            dgvSL2.AddColumn("序号", "ID", 10);
            dgvSL2.AddColumn("工程名称", "LampName", 20);
            dgvSL2.AddColumn("信号灯", "SignalLampMappingID", 20);
            dgvSL2.AddColumn("出发台数", "TriggerCount", 10);
            dgvSL2.AddColumn("出发延时台数", "TriggerDelayCount", 10);
            dgvSL2.AddColumn("结束延时台数", "EndDelayCount", 10);
            dgvSL2.AddColumn("单数/双数链", "ChainMark", 10);
            dgvSL2.AddColumn("状态", "Enable", 10);

            dgvSL3.AutoGenerateColumns = false;
            dgvSL3.AllowUserToAddRows = false;
            dgvSL3.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL3.ReadOnly = true;
            dgvSL3.AddColumn("序号", "ID", 10);
            dgvSL3.AddColumn("工程名称", "LampName", 20);
            dgvSL3.AddColumn("信号灯", "SignalLampMappingID", 20);
            dgvSL3.AddColumn("出发台数", "TriggerCount", 10);
            dgvSL3.AddColumn("出发延时台数", "TriggerDelayCount", 10);
            dgvSL3.AddColumn("结束延时台数", "EndDelayCount", 10);
            dgvSL3.AddColumn("单数/双数链", "ChainMark", 10);
            dgvSL3.AddColumn("状态", "Enable", 10);

            dgvSL4.AutoGenerateColumns = false;
            dgvSL4.AllowUserToAddRows = false;
            dgvSL4.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL4.ReadOnly = true;
            dgvSL4.AddColumn("序号", "ID", 10);
            dgvSL4.AddColumn("工程名称", "LampName", 20);
            dgvSL4.AddColumn("信号灯", "SignalLampMappingID", 20);
            dgvSL4.AddColumn("出发台数", "TriggerCount", 10);
            dgvSL4.AddColumn("出发延时台数", "TriggerDelayCount", 10);
            dgvSL4.AddColumn("结束延时台数", "EndDelayCount", 10);
            dgvSL4.AddColumn("单数/双数链", "ChainMark", 10);
            dgvSL4.AddColumn("状态", "Enable", 10);

            dgvSL5.AutoGenerateColumns = false;
            dgvSL5.AllowUserToAddRows = false;
            dgvSL5.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvSL5.ReadOnly = true;
            dgvSL5.AddColumn("序号", "ID", 10);
            dgvSL5.AddColumn("工程名称", "LampName", 20);
            dgvSL5.AddColumn("信号灯", "SignalLampMappingID", 20);
            dgvSL5.AddColumn("出发台数", "TriggerCount", 10);
            dgvSL5.AddColumn("出发延时台数", "TriggerDelayCount", 10);
            dgvSL5.AddColumn("结束延时台数", "EndDelayCount", 10);
            dgvSL5.AddColumn("单数/双数链", "ChainMark", 10);
            dgvSL5.AddColumn("状态", "Enable", 10);

            LoadDgvKK();
            LoadDgvMD();
            LoadDgvSL();
        }

        /// <summary>
        /// 加载开捆设置
        /// </summary>
        private void LoadDgvKK()
        {
            dgvKk.DataSource = null;
            dgvKk.DataSource = GolbalVariable.UnpackingDirectionBag.Where(x => x.DataType == "链数").OrderBy(x => x.ID).ToList();
            DgvUpadteEvent?.BeginInvoke(null,null);
        }

        /// <summary>
        /// 加载部品顺引设置
        /// </summary>
        private void LoadDgvMD()
        {
            GolbalVariable.MaterialDirectionBag = new ConcurrentBag<MaterialDirectionModel>(bllMaterialDirection.GetModelList());
            dgvDmsy.DataSource =null;
            dgvXmsy.DataSource =null;
            dgvZwsy.DataSource =null;
            dgvNzp.DataSource = null;
            dgvPx.DataSource = null;
            dgvDmsy.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 1).OrderBy(x => x.ID).ToList();
            dgvXmsy.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 2).OrderBy(x => x.ID).ToList();
            dgvZwsy.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 3).OrderBy(x => x.ID).ToList();
            dgvNzp.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 4).OrderBy(x => x.ID).ToList();
            dgvPx.DataSource = GolbalVariable.MaterialDirectionBag.Where(x => x.TypeId == 5).OrderBy(x => x.ID).ToList();
            DgvUpadteEvent?.BeginInvoke(null, null);
        }

        /// <summary>
        /// 加载信号灯设置
        /// </summary>
        private void LoadDgvSL()
        {
            //初始化全局变量
            List<UnpackingDirectionModel> unpackingDirectionList = bllUnpackingDirection.GetModelList();
            GolbalVariable.SignalLampShowModelBag = new ConcurrentBag<SignalLampShowModel>();
            foreach (var signalLamp in GolbalVariable.SignalLampDirectionBag)
            {
                var unpacking = unpackingDirectionList.Where(p => p.ID == signalLamp.UnpackingId).FirstOrDefault();
                var signalLampAddress = GolbalVariable.SignalLampMappingList.Where(s=>s.ID == signalLamp.SignalLampMappingID).FirstOrDefault();
                if (unpacking != null)
                {
                    SignalLampShowModel model = new SignalLampShowModel
                    {
                        Id = signalLamp.ID,
                        LampId = signalLamp.ID,
                        PullingRopeName = signalLamp.LampName,
                        ChainMark = signalLamp.ChainMark,
                        PullingRopeInAddress = signalLampAddress.ControlInputAddress,
                        GreenOutAddress = signalLampAddress.GreenOutputAddress,
                        RedOutAddress = signalLampAddress.RedOutputAddress,
                        TypeId = signalLamp.TypeId
                    };
                    GolbalVariable.SignalLampShowModelBag.Add(model);
                }
            }
            dgvSL0.DataSource = null;
            dgvSL1.DataSource = null;
            dgvSL2.DataSource = null;
            dgvSL3.DataSource = null;
            dgvSL4.DataSource = null;
            dgvSL5.DataSource = null;
            dgvSL0.DataSource = GolbalVariable.SignalLampDirectionBag.Where(x => x.TypeId == 0).OrderBy(x => x.ID).ToList();
            dgvSL1.DataSource = GolbalVariable.SignalLampDirectionBag.Where(x => x.TypeId == 1).OrderBy(x => x.ID).ToList();
            dgvSL2.DataSource = GolbalVariable.SignalLampDirectionBag.Where(x => x.TypeId == 2).OrderBy(x => x.ID).ToList();
            dgvSL3.DataSource = GolbalVariable.SignalLampDirectionBag.Where(x => x.TypeId == 3).OrderBy(x => x.ID).ToList();
            dgvSL4.DataSource = GolbalVariable.SignalLampDirectionBag.Where(x => x.TypeId == 4).OrderBy(x => x.ID).ToList();
            dgvSL5.DataSource = GolbalVariable.SignalLampDirectionBag.Where(x => x.TypeId == 5).OrderBy(x => x.ID).ToList();
            DgvUpadteEvent?.BeginInvoke(null, null);
        }

        /// <summary>
        /// 开捆参数设置
        /// </summary>
        /// <param name="entityMaterialDirection">开捆对象</param>
        private void unpackingEdit(UnpackingDirectionModel model = null)
        {
            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;

            if (model != null)
            {
                option.Text = "参数设置(" + model.UnpackingName + ")";
                option.AddText("UnpackingName", "工程名称", model.UnpackingName, true);
                option.AddText("IpAddress", "IP地址", model.IpAddress, false);
                //option.AddText("TriggerCount", "位置", null, false);
            }else
            {
                option.Text = "新增开捆";
                option.AddText("UnpackingName", "工程名称", null, true);
                option.AddText("IpAddress", "IP地址", null, false);
                //option.AddText("TriggerCount", "位置", null, false);
            }


            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();

            if (frm.IsOK)
            {
                if(model != null)
                {
                    model.UnpackingName = frm["UnpackingName"].ToString();
                    model.IpAddress = frm["IpAddress"].ToString();
                    if (bllUnpackingDirection.Update(model).IsSuccess)
                    {
                        UIMessageTip.ShowOk("修改成功");
                        LogObj.Info("修改开捆工程成功(" + model.UnpackingName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                    else
                    {
                        UIMessageBox.ShowError("修改失败！");
                        LogObj.Error("修改开捆工程失败(" + model.UnpackingName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                }
                else
                {
                    model = new UnpackingDirectionModel();
                    model.UnpackingName = frm["UnpackingName"].ToString();
                    model.IpAddress = frm["IpAddress"].ToString();
                    if (bllUnpackingDirection.Add(model).IsSuccess)
                    {
                        UIMessageTip.ShowOk("新增成功");
                        LogObj.Info("新增开捆工程成功(" + model.UnpackingName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                    else
                    {
                        UIMessageBox.ShowError("新增失败！");
                        LogObj.Error("新增开捆工程失败(" + model.UnpackingName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                }
            }
            frm.Dispose();
            LoadDgvKK();
        }

        /// <summary>
        /// 顺引顺建/内制品/排序工程参数设置
        /// </summary>
        /// <param name="entityMaterialDirection">部品对象</param>
        private void materialDirectionEdit(MaterialDirectionModel model = null, int typeId = 0)
        {
            //var var = GolbalVariable.OpcTagBag.Where(x => x.GroupId == 1).ToArray();
            //var signalMarks = GolbalVariable.OpcTagBag.Where(x => x.GroupId == 1).Select(x => x.SignalMark).ToArray();
            var triaGroups = GolbalVariable.TriaGroupList.Where(x => x.SignalMark == "LIP" || x.SignalMark == "TS").Select(x => x.ID).ToArray();
            var var = GolbalVariable.TriaItemList.Where(s => triaGroups.Contains(s.GroupID)).ToList();
            var signalMarks = GolbalVariable.TriaItemList.Where(s=> triaGroups.Contains(s.GroupID)).Select(x => x.SignalMark).ToArray();
            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;
            if (model != null)
            {
                option.Text = "参数设置(" + model.MaterialName + ")";
                option.AddText("MaterialName", "工程名称", model.MaterialName, true);
                option.AddText("IpAddress", "IP地址", model.IpAddress, false);
                option.AddInteger("ProjectCount", "工程台数", model.ProjectCount, true);
                option.AddInteger("StartTransportCount", "出发台数", model.StartTransportCount, true);
                if (typeId == 4 || model.TypeId == 4)
                    option.AddInteger("TriggerProjectCount", "出发工程工程数", model.TriggerProjectCount, true); //内制品多一个工程数
                option.AddText("CarMark", "车型标识", model.CarMark, false);
                option.AddCombobox("SignalMark", "信号源标识", var, "SignalMark", "SignalMark", model.SignalMark);
            }
            else
            {
                option.Text = "新增工程";
                option.AddText("MaterialName", "工程名称", null, true);
                option.AddText("IpAddress", "IP地址", null, false);
                option.AddInteger("ProjectCount", "工程台数", 0, true);
                option.AddInteger("StartTransportCount", "出发台数", 0, true);
                if (typeId == 4)
                    option.AddInteger("TriggerProjectCount", "出发工程工程数", 0, true); //内制品多一个工程数
                option.AddText("CarMark", "车型标识", null, false);
                option.AddCombobox("SignalMark", "信号源标识", signalMarks);
            }
            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();

            if (frm.IsOK)
            {
                if (model != null)
                {
                    model.MaterialName = frm["MaterialName"].ToString();
                    model.IpAddress = frm["IpAddress"].ToString();
                    model.ProjectCount = int.Parse(frm["ProjectCount"].ToString());
                    model.StartTransportCount = int.Parse(frm["StartTransportCount"].ToString());
                    model.CarMark = frm["CarMark"].ToString();
                    model.SignalMark = frm["SignalMark"].ToString();
                    if (typeId == 4 || model.TypeId == 4)
                        model.TriggerProjectCount = int.Parse(frm["TriggerProjectCount"].ToString()); //内制品多一个出发工程工程数

                    if (bllMaterialDirection.Update(model).IsSuccess)
                    {
                        UIMessageTip.ShowOk("修改成功");
                        LogObj.Info("修改顺引顺建/内制品/排序工程成功(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                    else
                    {
                        UIMessageBox.ShowError("修改失败！");
                        LogObj.Error("修改顺引顺建/内制品/排序工程失败(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                }
                else
                {
                    model = new MaterialDirectionModel();
                    model.MaterialName = frm["MaterialName"].ToString();
                    model.IpAddress = frm["IpAddress"].ToString();
                    model.ProjectCount = int.Parse(frm["ProjectCount"].ToString());
                    model.StartTransportCount = int.Parse(frm["StartTransportCount"].ToString());
                    model.CarMark = frm["CarMark"].ToString();
                    model.SignalMark = signalMarks[int.Parse(frm["SignalMark"].ToString())];
                    model.LeftCount = 0;
                    if (typeId == 4)
                        model.TriggerProjectCount = int.Parse(frm["TriggerProjectCount"].ToString()); //内制品多一个出发工程工程数
                    switch (typeId)
                    {
                        case 1:
                            model.TypeId = 1;
                            model.TypeName = "东面顺引工程";
                            break;
                        case 2:
                            model.TypeId = 2;
                            model.TypeName = "西面顺引工程";
                            break;
                        case 3:
                            model.TypeId = 3;
                            model.TypeName = "中物顺建工程";
                            break;
                        case 4:
                            model.TypeId = 4;
                            model.TypeName = "内制品工程";
                            break;
                        case 5:
                            model.TypeId = 5;
                            model.TypeName = "排序工程";
                            break;

                    }

                    if (bllMaterialDirection.Add(model).IsSuccess)
                    {
                        UIMessageTip.ShowOk("新增成功");
                        LogObj.Info("新增顺引顺建/内制品/排序工程成功(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                    else
                    {
                        UIMessageBox.ShowError("新增失败！");
                        LogObj.Error("新增顺引顺建/内制品/排序工程失败(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                }
            }
            frm.Dispose();
            LoadDgvMD();
        }

        /// <summary>
        /// 信号灯参数设置
        /// </summary>
        /// <param name="entityMaterialDirection">信号灯对象</param>
        private void signalLampEdit(SignalLampDirectionModel model = null,int typeId = 0)
        {
            //var var = GolbalVariable.OpcTagBag.Where(x => x.GroupId == 300001).ToArray();
            var LSDGroup = GolbalVariable.TriaGroupList.Where(x => x.SignalMark == "LSD").Select(x => x.ID).ToArray();
            var LSZTGroup = GolbalVariable.TriaGroupList.Where(x => x.SignalMark == "LSZT").Select(x => x.ID).ToArray();
            //var LSDsignalMarkList = GolbalVariable.TriaItemList.Where(s => LSDGroup.Contains(s.GroupID)).ToList();
            //var LSZTsignalMarkList = GolbalVariable.TriaItemList.Where(s => LSZTGroup.Contains(s.GroupID)).ToList();
            //var LSDsignalMarks = GolbalVariable.TriaItemList.Where(s => LSDGroup.Contains(s.GroupID)).Select(x => x.SignalMark).ToArray();
            //var LSZTsignalMarks = GolbalVariable.TriaItemList.Where(s => LSZTGroup.Contains(s.GroupID)).Select(x => x.SignalMark).ToArray();
            var LSDsignalMarks = GolbalVariable.SignalLampMappingList.Select(x => x.Name).ToArray();
            var unpackingDirections = GolbalVariable.UnpackingDirectionBag.Where(x => x.DataType == "台数").ToList();

            string[] chainMarkTypeNames = new[] { "全部", "单链", "双链"};
            string[] statuNames = new[] { "停用" ,"启用"};
            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;
            if(model != null)
            {
                option.Text = "参数设置(" + model.LampName + ")";
                option.AddText("LampName", "工程名称", model.LampName, true);
                option.AddCombobox("UnpackingName", "开捆类型", unpackingDirections, "UnpackingName", "ID", model.UnpackingId,false);
                //option.AddCombobox("ControlInputAddress", "拉绳输入地址", LSZTsignalMarkList, "SignalMark", "SignalMark", entitySignalLampDirection.ControlInputAddress);
                //option.AddCombobox("GreenOutputAddress", "绿灯输出地址", LSDsignalMarkList, "SignalMark", "SignalMark", entitySignalLampDirection.GreenOutputAddress);
                //option.AddCombobox("RedOutputAddress", "红灯输出地址", LSDsignalMarkList, "SignalMark", "SignalMark", entitySignalLampDirection.RedOutputAddress);
                option.AddCombobox("SignalLampName", "信号灯名称", GolbalVariable.SignalLampMappingList, "Name", "ID", model.SignalLampMappingID);
                option.AddInteger("TriggerCount", "出发台数", model.TriggerCount, true);
                option.AddInteger("TriggerDelayCount", "出发延时台数", model.TriggerDelayCount, true);
                option.AddInteger("EndDelayCount", "结束延时台数", model.EndDelayCount, true);
                option.AddCombobox("ChainMark", "单数/双数链", chainMarkTypeNames, int.Parse(model.ChainMark), true, true);
                option.AddCombobox("Enable", "状态", statuNames, model.Enable, true, true);
            }
            else
            {
                option.Text = "新增拉绳灯";
                option.AddText("LampName", "工程名称", null, true);
                option.AddCombobox("UnpackingName", "开捆类型", unpackingDirections, "UnpackingName", "ID", unpackingDirections.Where(s=> s.TypeId == typeId).FirstOrDefault().ID,false);
                //option.AddCombobox("ControlInputAddress", "拉绳输入地址", LSZTsignalMarks);
                //option.AddCombobox("GreenOutputAddress", "绿灯输出地址", LSDsignalMarks);
                //option.AddCombobox("RedOutputAddress", "红灯输出地址", LSDsignalMarks);
                option.AddCombobox("SignalLampName", "信号灯名称", LSDsignalMarks);
                option.AddInteger("TriggerCount", "出发台数", 0, true);
                option.AddInteger("TriggerDelayCount", "出发延时台数", 0, true);
                option.AddInteger("EndDelayCount", "结束延时台数", 0, true);
                option.AddCombobox("ChainMark", "单数/双数链", chainMarkTypeNames, 0, true, true);
                option.AddCombobox("Enable", "状态", statuNames, 1, true, true);
            }

            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();

            if (frm.IsOK)
            {
                var unpackingDirection = GolbalVariable.UnpackingDirectionBag.Where(x => x.ID == int.Parse(frm["UnpackingName"].ToString())).FirstOrDefault();
                if (model != null)
                {
                    model.LampName = frm["LampName"].ToString();
                    model.SignalLampMappingID = long.Parse(frm["SignalLampName"].ToString());
                    model.TriggerCount = int.Parse(frm["TriggerCount"].ToString());
                    model.TriggerDelayCount = int.Parse(frm["TriggerDelayCount"].ToString());
                    model.EndDelayCount = int.Parse(frm["EndDelayCount"].ToString());
                    model.ChainMark = frm["ChainMark"].ToString();
                    model.Enable = int.Parse(frm["Enable"].ToString());
                    model.TypeId = unpackingDirection.TypeId;
                    model.TypeName = unpackingDirection.UnpackingName;
                    model.UnpackingId = unpackingDirection.ID;

                    if (bllSignalLampDirection.Update(model).IsSuccess)
                    {
                        UIMessageTip.ShowOk("设置成功");
                        LogObj.Info("拉绳灯参数设置成功(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                    else
                    {
                        UIMessageBox.ShowError("设置失败！");
                        LogObj.Error("设置拉绳灯失败(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                }
                else
                {
                    model = new SignalLampDirectionModel();
                    model.LampName = frm["LampName"].ToString();
                    model.SignalLampMappingID = GolbalVariable.SignalLampMappingList.Where(x=> x.Name == LSDsignalMarks[int.Parse(frm["SignalLampName"].ToString())]).FirstOrDefault().ID;
                    model.TriggerCount = int.Parse(frm["TriggerCount"].ToString());
                    model.TriggerDelayCount = int.Parse(frm["TriggerDelayCount"].ToString());
                    model.EndDelayCount = int.Parse(frm["EndDelayCount"].ToString());
                    model.UnpackingId = int.Parse(frm["UnpackingName"].ToString());
                    model.ChainMark = frm["ChainMark"].ToString();
                    model.Enable = int.Parse(frm["Enable"].ToString());
                    model.TypeId = unpackingDirection.TypeId;
                    model.TypeName = unpackingDirection.UnpackingName;
                    model.UnpackingId = unpackingDirection.ID;

                    var result = bllSignalLampDirection.GetModelByNameOrSpecMark(model.LampName,model.SignalLampMappingID);
                    if(result.Count>0)
                    {
                        UIMessageBox.ShowError("信号灯名称或信号灯重复，请检查后才添加！");
                    }
                    else
                    {
                        if (bllSignalLampDirection.Add(model).IsSuccess)
                        {
                            GolbalVariable.SignalLampDirectionBag.Add(model);
                            UIMessageTip.ShowOk("新增成功");
                            LogObj.Info("新增拉绳灯成功(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                        }
                        else
                        {
                            UIMessageBox.ShowError("新增失败！");
                            LogObj.Error("新增拉绳灯失败(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                        }
                    }
                }
            }
            frm.Dispose();
            LoadDgvSL();
        }

        /// <summary>
        /// 开捆工程删除
        /// </summary>
        /// <param name="entityUnpackingDirection"></param>
        private void unpackingDelect(UnpackingDirectionModel model)
        {
            if (bllUnpackingDirection.Delete(model).IsSuccess)
            {
                UIMessageTip.ShowOk("删除成功");
                LogObj.Info("开捆工程删除成功(" + model.UnpackingName + ");作业者:"+ ApplicationCache.CurrentUser.LoginName);
            }
            else
            {
                UIMessageBox.ShowError("删除失败！");
                LogObj.Error("开捆工程删除失败(" + model.UnpackingName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
            }
            LoadDgvKK();
        }

        /// <summary>
        /// 顺引顺建工程删除
        /// </summary>
        /// <param name="entityMaterialDirection"></param>
        private void materialDirectionDelect(MaterialDirectionModel model)
        {
            if (bllMaterialDirection.Delete(model).IsSuccess)
            {
                UIMessageTip.ShowOk("删除成功");
                LogObj.Info("顺引顺建工程删除成功(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
            }
            else
            {
                UIMessageBox.ShowError("删除失败！");
                LogObj.Error("顺引顺建工程删除失败(" + model.MaterialName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
            }
            LoadDgvMD();
        }

        /// <summary>
        /// 拉绳灯删除
        /// </summary>
        /// <param name="entitySignalLampDirection"></param>
        private void signalLampDelect(SignalLampDirectionModel model)
        {
            if (bllSignalLampDirection.Delete(model).IsSuccess)
            {
                UIMessageTip.ShowOk("删除成功");
                LogObj.Info("拉绳灯删除成功(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
            }
            else
            {
                UIMessageBox.ShowError("删除失败！");
                LogObj.Error("拉绳灯删除失败(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
            }
            LoadDgvSL();
        }

        /// <summary>
        /// 顺引顺建/内制品/排序工程参数设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDmsy_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvDmsy.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvXmsy_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvXmsy.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvZwsy_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvZwsy.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvNzp_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvNzp.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvPx_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                materialDirectionEdit(dgvPx.CurrentRow.DataBoundItem as MaterialDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        /// <summary>
        /// 拉绳灯参数设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvRdcf_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                signalLampEdit(dgvSL0.CurrentRow.DataBoundItem as SignalLampDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvTjshzgcf_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                signalLampEdit(dgvSL1.CurrentRow.DataBoundItem as SignalLampDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvPcjhcf_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                signalLampEdit(dgvSL2.CurrentRow.DataBoundItem as SignalLampDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvFxdwcf_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                signalLampEdit(dgvSL3.CurrentRow.DataBoundItem as SignalLampDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvCxdwcf_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                signalLampEdit(dgvSL4.CurrentRow.DataBoundItem as SignalLampDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvXwcf_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                signalLampEdit(dgvSL5.CurrentRow.DataBoundItem as SignalLampDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        /// <summary>
        /// 开捆设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvKk_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
                unpackingEdit(dgvKk.CurrentRow.DataBoundItem as UnpackingDirectionModel);
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        #region 重置按钮方法
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            pictureBox1.Image = Properties.Resources.cz3;
        }

        private void pictureBox1_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.cz2;
        }

        private void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.cz1;
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            pictureBox1.Image = Properties.Resources.cz2;

            if (ApplicationCache.CurrentUser.Permission == 0)
            {
                bool result = true;
                result = UIMessageDialog.ShowMessageDialog("是否确定重置所有安灯拉绳？", UILocalize.AskTitle, true, UIStyle.Red, true, Frame?.TopMost ?? false);
                if (result)
                {
                    logisticsAndongHandler.ResetSignalLamp();
                }
                else
                {
            
                }
            }
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");

        }
        #endregion 

        UIDataGridView dataGridView;
         private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    dataGridView = (UIDataGridView)sender;
                    //若行已是选中状态就不再进行设置
                    if (dataGridView.Rows[e.RowIndex].Selected == false)
                    {
                        dataGridView.ClearSelection();
                        dataGridView.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dataGridView.SelectedRows.Count == 1)
                    {
                        dataGridView.CurrentCell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    //弹出操作菜单
                    uiContextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                }
                else
                {
                    dataGridView = (UIDataGridView)sender;
                    //弹出操作菜单
                    uiContextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        private void FrmSystemSet_SizeChanged(object sender, EventArgs e)
        {
            //asc.controlAutoSize(this.tabPage9);
            pictureBox1.Size = new Size(this.Height / 2, this.Height/2);
            pictureBox1.Location = new Point((this.Width - this.Height / 2) / 2, (this.Height - this.Height / 2) / 2);
        }

        private void toolStripMenuItemUpdata_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
            {
                if (dataGridView == null || dataGridView.CurrentRow == null)
                    return;
                //不同的dataGridView显示不同的编辑窗体
                switch (dataGridView.Name)
                {
                    case "dgvKk":
                        unpackingEdit(dataGridView.CurrentRow.DataBoundItem as UnpackingDirectionModel);
                        break;
                    case "dgvDmsy":
                        materialDirectionEdit(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel,1);
                        break;
                    case "dgvXmsy":
                        materialDirectionEdit(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel, 2);
                        break;
                    case "dgvZwsy":
                        materialDirectionEdit(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel, 3);
                        break;
                    case "dgvNzp":
                        materialDirectionEdit(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel, 4);
                        break;
                    case "dgvPx":
                        materialDirectionEdit(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel, 5);
                        break;
                    case "dgvSL0":
                        signalLampEdit(dataGridView.CurrentRow.DataBoundItem as SignalLampDirectionModel, 0);
                        break;
                    case "dgvSL1":
                        signalLampEdit(dataGridView.CurrentRow.DataBoundItem as SignalLampDirectionModel, 1);
                        break;
                    case "dgvSL2":
                        signalLampEdit(dataGridView.CurrentRow.DataBoundItem as SignalLampDirectionModel, 2);
                        break;
                    case "dgvSL3":
                        signalLampEdit(dataGridView.CurrentRow.DataBoundItem as SignalLampDirectionModel, 3);
                        break;
                    case "dgvSL4":
                        signalLampEdit(dataGridView.CurrentRow.DataBoundItem as SignalLampDirectionModel, 4);
                        break;
                    case "dgvSL5":
                        signalLampEdit(dataGridView.CurrentRow.DataBoundItem as SignalLampDirectionModel, 5);
                        break;

                }
            }
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
            {
                if (dataGridView == null)
                    return;
                //添加方法
                //不同的dataGridView显示不同的添加窗体
                switch (dataGridView.Name)
                {
                    case "dgvKk":
                        //unpackingEdit();
                        UIMessageBox.ShowWarning("该操作目前不允许！");
                        break;
                    case "dgvDmsy":
                        materialDirectionEdit(null, 1);
                        break;
                    case "dgvXmsy":
                        materialDirectionEdit(null, 2);
                        break;
                    case "dgvZwsy":
                        materialDirectionEdit(null, 3);
                        break;
                    case "dgvNzp":
                        materialDirectionEdit(null, 4);
                        break;
                    case "dgvPx":
                        materialDirectionEdit(null, 5);
                        break;

                    case "dgvSL0":
                        //signalLampEdit(null, 0);
                        UIMessageBox.ShowWarning("该操作目前不允许！");
                        break;
                    case "dgvSL1":
                        signalLampEdit(null, 1);
                        break;
                    case "dgvSL2":
                        signalLampEdit(null, 2);
                        break;
                    case "dgvSL3":
                        signalLampEdit(null, 3);
                        break;
                    case "dgvSL4":
                        signalLampEdit(null, 4);
                        break;
                    case "dgvSL5":
                        signalLampEdit(null, 5);
                        break;
                }
            }
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission == 0)
            {
                if (dataGridView == null || dataGridView.CurrentRow == null)
                    return;
                if (dataGridView.Name == "dgvKk")
                {
                    UIMessageBox.ShowWarning("该操作目前不允许！");
                    return;
                }
                if (UIMessageDialog.ShowMessageDialog("您确定要删除该工程吗？", UILocalize.AskTitle, true, UIStyle.Red, true, Frame?.TopMost ?? false))
                {
                    //删除方法
                    //不同的dataGridView显示不同的编辑窗体
                    switch (dataGridView.Name)
                    {
                        case "dgvDmsy":
                            materialDirectionDelect(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel);
                            break;
                        case "dgvXmsy":
                            materialDirectionDelect(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel);
                            break;
                        case "dgvZwsy":
                            materialDirectionDelect(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel);
                            break;
                        case "dgvNzp":
                            materialDirectionDelect(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel);
                            break;
                        case "dgvPx":
                            materialDirectionDelect(dataGridView.CurrentRow.DataBoundItem as MaterialDirectionModel);
                            break;
                        default:
                            signalLampDelect(dataGridView.CurrentRow.DataBoundItem as SignalLampDirectionModel);
                            break;

                    }
                }
                else
                {

                }
            }
            else
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
        }

        private void dgvRdcf_DataSourceChanged(object sender, EventArgs e)
        {

        }

        private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            if (e.ColumnIndex == 2)
            {
                e.FormattingApplied = true;
                DataGridViewRow row = dgv.Rows[e.RowIndex];
                if (row != null)
                {
                    var signalLamp = GolbalVariable.SignalLampMappingList.Where(s => s.ID == long.Parse(row.Cells[e.ColumnIndex].Value.ToString())).FirstOrDefault();
                    e.Value = string.Format("{0}",
                  signalLamp.Name);
                }
            }

            if (e.ColumnIndex == 6)
            {
                e.FormattingApplied = true;
                DataGridViewRow row = dgv.Rows[e.RowIndex];
                if (row != null)
                {
                    if (row.Cells[e.ColumnIndex].Value.ToString() == "0")
                    {
                        e.Value = string.Format("{0}",
                          "全部");
                    }
                    else if(row.Cells[e.ColumnIndex].Value.ToString() == "1")
                    {
                        e.Value = string.Format("{0}",
                      "单链");
                    }
                    else if (row.Cells[e.ColumnIndex].Value.ToString() == "2")
                    {
                        e.Value = string.Format("{0}",
                      "双链");
                    }
                }
            }
            if (e.ColumnIndex == 7)
            {
                e.FormattingApplied = true;
                DataGridViewRow row = dgv.Rows[e.RowIndex];
                if (row != null)
                {
                    if (row.Cells[e.ColumnIndex].Value.ToString() == "0")
                    {
                        e.Value = string.Format("{0}",
                          "停用");
                    }
                    else if (row.Cells[e.ColumnIndex].Value.ToString() == "1")
                    {
                        e.Value = string.Format("{0}",
                      "启用");
                    }
                }
            }
        }
    }
}
